﻿using System;
using System.Text;
using SocketCS;
using System.Configuration;
using System.Net;

namespace AccompanyCabinet.Helper
{

    public static class SocketHelper
    {
        private delegate void ConnectUpdateUiDelegate();
        private delegate void ShowMsg(string msg);
        public static TcpClient client = new TcpClient();
        public static string IDENTITY = ConfigurationManager.AppSettings["Identity"].ToString();

        /// <summary>
        /// 连接上位机
        /// </summary>
        public static void SocketConnect()
        {
            // 设置client事件
            client.OnPrepareConnect += new TcpClientEvent.OnPrepareConnectEventHandler(OnPrepareConnect);
            client.OnConnect += new TcpClientEvent.OnConnectEventHandler(OnConnect);
            client.OnSend += new TcpClientEvent.OnSendEventHandler(OnSend);
            client.OnReceive += new TcpClientEvent.OnReceiveEventHandler(OnReceive);
            client.OnClose += new TcpClientEvent.OnCloseEventHandler(OnClose);
            try
            {
                string ip = ConfigurationManager.AppSettings["ServerIP"].ToString();
                ushort port = Convert.ToUInt16(ConfigurationManager.AppSettings["ServerPort"]);
                //默认异步连接
                if (client.Connect(ip, port, true))
                {
                    LogHelper.WriteLog(string.Format("连接上位机时间为{0}.", DateTime.Now.ToString()));
                    SocketSend(new byte[] { 0x30,0x31 });
                }
                else
                {
                    //记录错误日志
                    LogHelper.WriteLog(string.Format("{0}.", DateTime.Now.ToString()), new Exception(string.Format("{0}_({1})", client.ErrorMessage, client.ErrorCode)));
                    throw new Exception(string.Format(" {0}_({1})", client.ErrorMessage, client.ErrorCode));
                }
            }
            catch (Exception ex)
            {
                //记录错误日志
                LogHelper.WriteLog(string.Format("当前时间为{0}.", DateTime.Now.ToString()), ex);
            }
        }

        /// <summary>
        /// 断开上位机
        /// </summary>
        public static void SocketClose()
        {
            // 停止服务
            if (client.Stop())
            {
                LogHelper.WriteLog(string.Format("断开上位机时间为{0}.", DateTime.Now.ToString()));
            }
            else
            {
                //记录错误日志
                LogHelper.WriteLog(string.Format("当前时间为{0}.", DateTime.Now.ToString()), new Exception(string.Format("{0}_({1})", client.ErrorMessage, client.ErrorCode)));
            }
        }

        /// <summary>
        /// 发送内容
        /// </summary>
        /// <param name="sendContent">发送内容；字符串</param>
        /// <returns></returns>
        public static bool SocketSend(byte[] bytes)
        {
            if (bytes == null || bytes.Length == 0) return true;
            var sendBuff = new byte[bytes.Length + 6];
            Array.Copy(BitConverter.GetBytes(sendBuff.Length), sendBuff, 4);
            Array.Copy(bytes,0, sendBuff, 4, bytes.Length);
            sendBuff[sendBuff.Length - 2] = 0x0D;
            sendBuff[sendBuff.Length - 1] = 0x0A;
            return client.Send(sendBuff, sendBuff.Length);
        }



        #region HandleResult
        static HandleResult OnPrepareConnect(TcpClient sender, IntPtr socket)
        {
            return HandleResult.Ok;
        }

        static HandleResult OnConnect(TcpClient sender)
        {
            return HandleResult.Ok;
        }

        static HandleResult OnSend(TcpClient sender, byte[] bytes)
        {
            return HandleResult.Ok;
        }

        static HandleResult OnReceive(TcpClient sender, byte[] bytes)
        {
            return HandleResult.Ok;
        }

        static HandleResult OnClose(TcpClient sender, SocketOperation enOperation, int errorCode)
        {
            if (errorCode == 0)
                LogHelper.WriteLog(string.Format(" > [{0},OnClose]", sender.ConnectionId));
            else
                // 出错了
                LogHelper.WriteLog(string.Format(" > [{0},OnError] -> OP:{1},CODE:{2}", sender.ConnectionId, enOperation, errorCode));
            return HandleResult.Ok;
        }

        #endregion



    }
}
